<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\User;
use app\admin\model\MpOfficial;
use app\admin\model\Configuration;
use app\admin\model\MobileCode;
use app\admin\model\Relation;
use app\admin\model\Coupon;
use app\admin\model\GroupChat;
use app\admin\model\GroupChatUser;
use app\admin\model\Category;
use app\admin\model\ProductCategory;
use app\admin\model\MpType;
use app\admin\model\Shop;
use app\admin\model\Noviceguide;
use app\admin\model\MpMp;
use app\admin\model\Product;
use app\admin\model\Prize;
use app\admin\model\PrizeUser;
use app\admin\model\ProductMessage;
use app\admin\model\ProductWish;
use app\admin\model\Community;
use app\admin\model\ConfigData;
use app\admin\model\Article;
use app\admin\model\ProductViewLog;
use app\admin\model\UserRoseLog;
use app\admin\model\UserOrder;
use app\admin\model\AreaWorldwide;
use app\admin\model\MpModule;
use app\admin\model\Slideshow;
use app\admin\model\Version;
use app\admin\model\TaskImg;
use app\admin\model\Area;
use app\admin\model\EventStatistics;
use app\admin\model\EventStatisticsPage;
use app\admin\model\UserStatistics;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
use think\Db;
use think\Exception;


use Firebase\JWT\JWT;

/**
 * 首页接口
 */
class Index extends Api
{
    
   
	protected $sensitivity = '';
    protected $NeedLogin = ['add_task_img','getMoonshotAi']; //存在则验证token

	public function _initialize(){
		$action = request()->action();
	
		if(in_array($action,$this->NeedLogin)){
			$ignore = array('host','accept','content-length','content-type');
			$headers = array();
			if($this->request->request('token')){
				$headers['token'] = $this->request->request('token');
			}else{
				foreach($_SERVER as $key=>$value){
					if(substr($key, 0, 5)==='HTTP_'){
						$key = substr($key, 5);
						$key = str_replace('_', ' ', $key);
						$key = str_replace(' ', '-', $key);
						$key = strtolower($key);
						if(!in_array($key, $ignore)){
							$headers[$key] = $value;
						}
					}
				}
			}
			$token=$headers['token'];
			if(strlen($token)!=32){
				$this->error('请登录');
			}
			$this->user=User::where(array('token'=>$token))->find();
			if(!$this->user){
				$this->error('请登录');
			}
			if($this->user['status'] != 1){
                $this->error('账号异常');
            }
			User::where(array('id'=>$this->user['id']))->update(array('active_time'=>time()));
		}

		$this->configuration = Configuration::find();
	}


	//获取客服图片
	public function dy_pay_switch(){
		$this->success('操作成功',1);
	}
	//获取支付金额套餐
	public function scrollList(){
		$arr = [
			['id'=>1,'title'=>'不限制版','price'=>688,'yj'=>1688,'num'=>10000000,'lj_price'=>1000],
			['id'=>2,'title'=>'公司1人版','price'=>1,'yj'=>88,'num'=>1,'lj_price'=>87],
			['id'=>3,'title'=>'公司15人版','price'=>45,'yj'=>188,'num'=>5,'lj_price'=>143],
			['id'=>4,'title'=>'公司10人版','price'=>80,'yj'=>288,'num'=>10,'lj_price'=>218],
			['id'=>5,'title'=>'公司30人版','price'=>220,'yj'=>488,'num'=>30,'lj_price'=>268],
			['id'=>6,'title'=>'公司50人版','price'=>300,'yj'=>688,'num'=>50,'lj_price'=>388],
		];
		$this->success('操作成功',$arr);
	}

	//	
	public function getKfImg(){
		$this->success('操作成功','https://oa.yuxiang123.cn/assets/portrait/kefu.jpg');
    }


	//获取首页xx人制作 xx人访问  xx人分享
	public function getInfo(){
        $make_num = MpType::sum('make_num');
        $visit_num = MpType::sum('visit_num');
        $share_num = MpType::sum('share_num');
		$this->success('操作成功',['share_num'=>$share_num,'make_num'=>$make_num,'visit_num'=>$visit_num]);
    }
	
	//获取模块
	public function getMpModule(){
		$id = $this->request->request('id','');
        $list = MpModule::select();
		$module = MpType::where(['id'=>$id])->value('module');
		$module = explode(',',$module);
		foreach ($list as &$v) {
			if(in_array($v['id'],$module)){
				$v['status'] = 2;
			}
		}
		$this->success('操作成功',$list);
    }
	

	//获取名片详情
    public function getMpInfo(){
        $id = $this->request->request('id','');
        if(!$id){
            $this->error('参数错误');
        }
        $info = MpMp::where(['id'=>$id,'status'=>1])->find();
        if(!$info){
            $this->error('参数错误');
        }
		$info['case_imgs_list'] = explode(',',$info['case_imgs']);
        $this->success('操作成功',$info);
    }


	//获取官方内容
	public function official(){
		$id = $this->request->request('id','');
		if($id){
			$info = MpOfficial::where(['id'=>$id])->find();
			$info['add_time'] = date('Y-m-d H:i:s',$info['add_time']);
			$info['content'] = htmlspecialchars_decode($info['content']);
			$this->success('操作成功',$info);
		}else{
			$list = MpOfficial::order('id desc')->limit('0,5')->select();
			foreach ($list as &$v) {
			
				$v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
			}
			$this->success('操作成功',$list);	
		}
		
	}
	
	//获取名片分类	
	public function getType(){
		$id = $this->request->request('id','');
		$page = $this->request->request('page','');
		$pagesize = $this->request->request('pagesize','');
		$big_id = $this->request->request('big_id','');
		if($id){
			$info = MpType::where(['id'=>$id])->find();
			$info['add_time'] = date('Y-m-d H:i:s',$info['add_time']);
			$this->success('操作成功',$info);
		}else{
			$where = ['status'=>1];
			if($big_id){
				$where['type'] = $big_id;
			}
			$list = MpType::order('add_time desc')->where($where)->order('id desc')->limit(($page-1)*$pagesize,$pagesize)->select();
			foreach ($list as &$v) {
				$v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
			}
			$this->success('操作成功',$list);
		}
	}
	
	//获取名片大类
	public function getBigType(){
		$info = [
			['id'=>2,'name'=>'企业公司'],
			['id'=>4,'name'=>'电商行业'],
			['id'=>3,'name'=>'实体店铺'],
			['id'=>1,'name'=>'个人模版'],
		];
		$this->success('操作成功',$info);
	}
	


	  /***
     * 生成二维码
     *
     */
    public function QRcode($url = "https://oa.yuxiang123.cn", $filename = 'createQR.png')
    {
        $writer = new PngWriter();
        //创建实例
        $qrCode = QrCode::create($url)
            ->setSize(300)
            ->setMargin(10)
            ->setEncoding(new Encoding('UTF-8'))
            ->setErrorCorrectionLevel(new ErrorCorrectionLevelHigh());
		//        //logo
		//        $logo = Logo::create(ROOT_PATH.'/public/static/image/qrlogo.png')->setResizeToWidth(50);
		//        //文字
		//        $label = Label::create($name);
        $result = $writer->write($qrCode);
        header('Content-Type: ' . $result->getMimeType());
        $result->saveToFile(ROOT_PATH . '/public/uploads/qrcode/' . $filename);
        return '/uploads/qrcode/' . $filename;
    }

	//支付开关
	public function pay_switch(){
		$this->success('操作成功',1);
	}
	//ios图片上传开关
	public function img_switch(){
		$this->success('操作成功',-1);
	}


	//新增任务截图审核
	public function add_task_img(){
		$img = $this->request->request('img');
		$type = $this->request->request('type',0);
		if(!$img){
			$this->error('参数错误');
		}
		$time =  strtotime(date('Y-m-d',time()));
		$info = TaskImg::where(['user_id'=>$this->user['id'],'type'=>$type,'add_time'=>['>',$time],'status'=>['neq',-1]])->find();
		if($info){
			$this->error('请勿重复提交');
		}
		$data = [
			'user_id'=>$this->user['id'],
			'img'=>$img,
			'type'=>$type,
			'add_time'=>time()
		];
		TaskImg::insert($data);
		$this->success('上传成功,请等待审核');
	}

	//统计页面
	public function addEventStatisticsPage(){
		$user_id = $this->request->request('user_id',0);
		$event = $this->request->request('event','');
		$type = $this->request->request('type','xcx');
		if(!$user_id){
			return;
		}
		$arr = [
			'首页','商品详情','心愿池','心愿池详情','新手引导','活动抽奖','社区','社区详情','消息','我的','我送出的','我领取的','我发布的','搜索','我的积分','积分任务','邀请好友','地址管理','常见问题','浏览记录','我的收藏','个人中心','个人资料','确认订单','发布闲置','发布心愿','发布社区'
		];
		//判断页面是否满足
		if(!in_array($event,$arr)){
			return;
		}
		if($type != 'xcx' &&  $type != 'app'){
			return;
		}
		$info = EventStatisticsPage::where(['user_id'=>$user_id,'type'=>$type,'event'=>$event])->find();
		if($info){
			EventStatisticsPage::where(['id'=>$info['id']])->update(['sum'=>$info['sum']+1]);
		}else{
			EventStatisticsPage::insert(['type'=>$type,'event'=>$event,'user_id'=>$user_id,'sum'=>1,'add_time'=>time(),'day'=>date('Y-m-d',time())]);
		}
	}
	
	 /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $code 验证码
     * @param string $invite_user_id 上级id
     */
    public function register()
    {
		$login_source = $this->request->request('login_source','xcx');
		$openid_code = $this->request->request('openid_code','');
        $password = $this->request->request('password','123456');
        $invite_user_id = $this->request->request('invite_user_id');
        $is_shop = $this->request->request('is_shop',0);
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        if (!$password) {
            $this->error(__('Invalid parameters'));
        }
		$mobile_code=MobileCode::where(array('mobile'=>$mobile,'verify'=>0))->order('add_time desc')->limit(0,1)->find();
		if($code!=$mobile_code['code'] && $code != 999999){
			$this->error('验证码错误');
		}

		if((!check_phone($mobile))){
			$mobile = str_replace('00447','07',$mobile);
			//判断是否是07开头  11位
			if(!($mobile[0] == 0 && $mobile[1] == 7 && strlen($mobile) == 11)){
				$this->error('请输入有效的手机号码');
			}
		}
		$userinfo = User::where(['mobile'=>$mobile,'is_shop'=>$is_shop])->find();
		if($userinfo){
			$this->error(__('该手机号已被注册'));
		}
		//第一次注册储存缓存 防止重复点击注册多个用户
		/* $redis = redis_init();
		$redis_name = 'register'.$mobile.time();
		$info = $redis->get($redis_name);
		if(!$info){
			$redis->set($redis_name,1);
		}else{
			$this->error('请勿重复点击');
		} */
		//账号注册时需要开启事务,避免出现垃圾数据
		Db::startTrans();
		try {
			//创建之前查询手机号是否已经注册  上锁  加锁  防止重复注册
			$user=User::where(array('mobile'=>$mobile,'status'=>['in','1,0'],'is_shop'=>$is_shop))->find();
			if($user){
				Db::commit();
				$this->error('请勿重复点击');
			}

			$openid = $openid_code ? $this->getOpenid($openid_code,1,$is_shop) : '';
			$nickname = $this->repetition_nickname('用户'.substr($mobile,7,4));
			$token=md5(md5(date("ymdHis").rand(100000,999999)));
			$user=array(
				'mobile'			=>$mobile,
				'invite_user_id'	=>$invite_user_id,
				'rose_money'		=>0,
				'password'		    =>md5($password),
				'nickname'			=>$nickname,
				'avatar'			=>'https://'.$_SERVER['HTTP_HOST'].'/assets/portrait/'.rand(1,17).'.png',
				'profile'			=>'',
				'gender'			=>0,
				'is_shop'			=>$is_shop,
				'openid'			=>$openid,
				'birthday'			=>'',
				'city'				=>'',
				'bgimg'				=>$this->configuration['default_bgimg'],
				'tags'				=>'',
				'weixin'			=>'',
				'login_source'		=> $invite_user_id ? 'new' : $login_source,
				'rose_money'		=>0,
				'read_message'		=>0,
				'follow_count'		=>0,
				'fans_count'		=>0,
				'love_count'		=>0,
				'token'				=>$token,
				'last_login_time'	=>time(),
				'add_time'			=>time(),
				'ip'                =>request()->ip()
			);
			
			$user_id=User::insertGetId($user);
			$user['id']=$user_id;
			if($is_shop == 0){
				if($this->configuration['register_rose_money']>0){
					//判断该用户是否是注销后的用户
					$info = User::where(['mobile'=>$mobile.'_2'])->find();
					if(!$info){
						roseandlog($user_id,$this->configuration['register_rose_money'],1,'注册奖励');
					}
				}
				if($invite_user_id>0 && $this->configuration['invite_rose_money']>0 ){
					roseandlog($invite_user_id,$this->configuration['invite_rose_money'],2,'邀请奖励');
				}


				$info = GroupChat::where(['number'=>['<',500]])->order('id asc')->find();
				if($info){
					GroupChatUser::insert(['user_id'=>$user_id,'group_chat_id'=>$info['id'],'grade'=>1,'add_time'=>time()]);
					GroupChat::where(['id'=>$info['id']])->update(['number'=>$info['number']+1]);
				}
			}else{
				//苏拉注册  查询是否有优惠卷
				$list = Coupon::where(['status'=>1,'type'=>1])->select();
				if($list){
					foreach ($list as $v) {
						$arr = ['user_id'=>$user_id,'coupon_id'=>$v['id'],'add_time'=>time()];
						UserCoupon::insert($arr);
					}
				}
			}
			//更新验证码状态
			MobileCode::where(['id'=>$mobile_code['id']])->update(['verify'=>1]);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error('操作失败');
		}
		$this->success('注册成功',['token'=>$token,'user'=>$user]);
    }


	/**
     * app 微信授权登录
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $code 验证码
     * @param string $invite_user_id 上级id
     */
    public function app_wx_login()
    {
		$login_source = $this->request->request('login_source','xcx');
        $invite_user_id = $this->request->request('invite_user_id');
        $is_shop = $this->request->request('is_shop',0);
        $openid = $this->request->request('openid','');
		if($openid){
			$info = User::where(array('openid'=>$openid,'status'=>1,'is_shop'=>$is_shop))->find();
			if(!$info){
				Db::startTrans();
				try {
					//创建之前查询手机号是否已经注册
					$nickname = $this->repetition_nickname('用户'.rand(100000,999999));
					$token=md5(md5(date("ymdHis").rand(100000,999999)));
					$user=array(
						'mobile'			=>'',
						'invite_user_id'	=>$invite_user_id,
						'rose_money'		=>0,
						'password'		    =>md5('123456'),
						'nickname'			=>$nickname,
						'avatar'			=>'https://'.$_SERVER['HTTP_HOST'].'/assets/portrait/'.rand(1,17).'.png',
						'profile'			=>'',
						'gender'			=>0,
						'is_shop'			=>$is_shop,
						'openid'			=>$openid,
						'birthday'			=>'',
						'city'				=>'',
						'bgimg'				=>$this->configuration['default_bgimg'],
						'tags'				=>'',
						'weixin'			=>'',
						'login_source'		=> $invite_user_id ? 'new' : $login_source,
						'rose_money'		=>0,
						'read_message'		=>0,
						'follow_count'		=>0,
						'fans_count'		=>0,
						'love_count'		=>0,
						'token'				=>$token,
						'last_login_time'	=>time(),
						'add_time'			=>time()
					);
					$user_id=User::insertGetId($user);
					$user['id']=$user_id;
					if($is_shop == 0){
						if($this->configuration['register_rose_money']>0){
							//判断该用户是否是注销后的用户
							$info = '';
							if($user['mobile']){
								$info = User::where(['mobile'=>$user['mobile'].'_2'])->find();
							}
							if(!$info){
								roseandlog($user_id,$this->configuration['register_rose_money'],1,'注册奖励');
							}
						}	
						if($invite_user_id>0 && $this->configuration['invite_rose_money']>0 ){
							roseandlog($invite_user_id,$this->configuration['invite_rose_money'],2,'邀请奖励');
						}

						$info = GroupChat::where(['number'=>['<',500]])->order('id asc')->find();
						if($info){
							GroupChatUser::insert(['user_id'=>$user_id,'group_chat_id'=>$info['id'],'grade'=>1,'add_time'=>time()]);
							GroupChat::where(['id'=>$info['id']])->update(['number'=>$info['number']+1]);
						}
					}else{
						//苏拉注册  查询是否有优惠卷
						$list = Coupon::where(['status'=>1,'type'=>1])->select();
						if($list){
							foreach ($list as $v) {
								$arr = ['user_id'=>$user_id,'coupon_id'=>$v['id'],'add_time'=>time()];
								UserCoupon::insert($arr);
							}
						}
					}
					
					Db::commit();
					$info = User::where(['id'=>$user_id])->find();
					$this->success('获取成功',['token'=>$token,'user'=>$info,'is_new'=>1]);
				} catch (Exception $e) {
					Db::rollback();
					$this->error('操作失败');
				}
			}
			$this->success('获取成功',['token'=>$info['token'],'user'=>$info,'is_new'=>0]);
		}else{
			$this->error('操作失败');
		}
    }
	 /**
	* 忘记密码
	*
	* @ApiMethod (POST)
	* @param string $username 用户名
	* @param string $password 密码
	*/
	public function forget_password()
	{
        $password = $this->request->post('password');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$password) {
            $this->error(__('Invalid parameters'));
        }
		$mobile_code=MobileCode::where(array('mobile'=>$mobile,'verify'=>0))->order('add_time desc')->limit(0,1)->find();
		if($code!=$mobile_code['code']){
			$this->error('验证码错误');
		}
		if((!check_phone($mobile))){
			$mobile = str_replace('00447','07',$mobile);
			//判断是否是07开头  11位
			if(!($mobile[0] == 0 && $mobile[1] == 7 && strlen($mobile) == 11)){
				$this->error('请输入有效的手机号码');
			}
		}
		//账号注册时需要开启事务,避免出现垃圾数据
		Db::startTrans();
		try {
			//创建之前查询手机号是否已经注册
			$user=User::where(array('mobile'=>$mobile,'status'=>['in','1,0']))->find();
			if(!$user){
				Db::commit();
				$this->error('未查询到账号');
			}
			//更新用户密码
			User::where(['id'=>$user['id']])->update(['password'=>md5($password)]);
			//更新验证码状态
			MobileCode::where(['id'=>$mobile_code['id']])->update(['verify'=>1]);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error('操作失败');
		}
		$this->success('操作成功',['token'=>$user['token'],'user'=>$user]);


    }


	//事件埋点
	public function addEventStatistics(){
		$type = $this->request->request('type','xcx');
		$user_id = $this->request->request('user_id',0);
		$event = $this->request->request('event','');
		// if($user_id == 'o_sKy5N0XBUBqa5hrSHRxqfIq5J4'){
		// 	return;
		// }
		$arr = [
			'发布闲置','心愿页','精选（首页）','半价寄件','离我最近','最新','去白拿','新人礼包','首页banner','商品详情页','我想要','心愿页','立即兑换','发布动态','发布心愿','手机号快捷登录','积分任务-分享','确认兑换按钮','确认订单页'
		];
		$Category = ProductCategory::where(array('pid'=>1,'status'=>'normal'))->select();
		foreach ($Category as $v) {
			$arr[] = '首页分类-'.$v['name'];
		}
		//判断埋点事件是否满足
		if(!in_array($event,$arr)){
			return;
		}
		if($type != 'xcx' &&  $type != 'app'){
			return;
		}
		$where = [
			'type'=>$type,
			'events'=>$event,
			'day'=>date('Y-m-d',time())
		];
		$res = EventStatistics::where($where)->find();
		if($res){
			$update = [
				'sum'=>$res['sum']+1
			];
			if($user_id && !in_array($user_id,explode(',',$res['user_id']))){
				$update['user_id'] = $res['user_id'].','.$user_id;
			}
			EventStatistics::where(['id'=>$res['id']])->update($update);
		}else{
			$where['add_time'] = time();
			EventStatistics::insert($where);
		}
 		return;
	}
	
    public function is_ship_num(){
        $ship_num= $this->request->request('ship_num');
        if(is_ship_num($ship_num)){
            exit('ok');
        }else{
            exit('格式不支持');
        }
    }
	/*
	*发送手验证码
	*/
    public function mobile_code(){
		$mobile = $_mobile = $this->request->request('mobile','');
		if(empty($mobile) || !check_phone($mobile)){
			//判断是否是07开头  11位
			if($mobile[0] == 0 && $mobile[1] == 7 && strlen($mobile) == 11){
				$mobile = '0044'.substr($mobile, 1);
				$repeat=MobileCode::where(array('mobile'=>$mobile,'verify'=>0,'add_time'=>array('gt',time()-60)))->find();
				if($repeat){
					$this->error('无需重复发送');
				}
				$res = send_mobile($mobile,'SMS_464750163');
				if($res['code'] == 1){
					MobileCode::insert(array('mobile'=>$mobile,'code'=>$res['code'],'verify'=>0,'add_time'=>time()));
					$this->success('发送成功');
				}else{
					$this->error($res['msg']);
				}
			}else{
				$this->error('请输入有效的手机号码');
			}
		}else{
            $repeat=MobileCode::where(array('mobile'=>$mobile,'verify'=>0,'add_time'=>array('gt',time()-60)))->find();
            if($repeat){
                $this->error('无需重复发送');
            }
			$res = send_mobile($mobile);
			if($res['code'] == 1){
				MobileCode::insert(array('mobile'=>$_mobile,'code'=>$res['phone'],'verify'=>0,'add_time'=>time()));
				$this->success('发送成功');
			}else{
				$this->error($res['msg']);
			}
			// $code=rand(100000,999999);
			// //发送短信验证码，待接入
			// $configuration=$this->configuration;
			// // 注意使用GMT时间  
			// date_default_timezone_set("GMT");  
			// $target = "https://dysmsapi.aliyuncs.com/?";  
			// $accessKeyId = $configuration['access_key'];      // 这里填写您的Access Key ID  
			// $accessKeySecret = $configuration['access_secret'];  // 这里填写您的Access Key Secret  
			// $ParamString="{\"code\":\"$code\"}";  
			// $data = [
			// 	'AccessKeyId' => $accessKeyId,
			// 	'Action' => 'SendSms',
			// 	'Format' => 'XML', 
			// 	'OutId' => '123', 
			// 	'PhoneNumbers' => $mobile,
			// 	'RegionId' => 'cn-hangzhou',
			// 	'SignName'=>$configuration['sign_name'],
			// 	'SignatureMethod' => 'HMAC-SHA1',
			// 	'SignatureNonce'=> '45e25e9b-0a6f-4070-8c85-'.uniqid(),
			// 	'SignatureVersion' => '1.0',
			// 	'TemplateCode' => $configuration['sms_mb'], 
			// 	'TemplateParam' => $ParamString,
			// 	'Timestamp' => date("Y-m-d H:i:s"),
			// 	'Version' => '2017-05-25'
            // ];  
			// $data['Signature'] = computeSignature($data, $accessKeySecret);  
			// // 发送请求  
			// $result = xml_to_array(https_request($target.http_build_query($data)));
			// if($result['Error']['Message']){
            //     $this->error($result['Error']['Message']);
			// }else{
			// 	MobileCode::insert(array('mobile'=>$mobile,'code'=>$code,'verify'=>0,'add_time'=>time()));
            //     $this->success('发送成功');
			// }
		}
    }
	
	//获取用户的openid
	public function getOpenid($code = '',$type = '',$is_shop = 0){

		if($type){
			if($is_shop){
				$appid = 'wx84f56a63b9f63e03';
				$secret = '98b698d6f873fdd2292684babd69c975';
			}else{
				$appid = 'wx84f56a63b9f63e03';
				$secret = '98b698d6f873fdd2292684babd69c975';
			}
			$res= file_get_contents('https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code');
			$res_a=json_decode($res,true);
			if(!$res_a['openid']){
				$this->error('获取失败');
			}
			$openid=$res_a['openid'];
			return $openid;
		}else{
			$code =   $this->request->request('code');
			$token =   $this->request->request('token','');
			$login =   $this->request->request('login','');
			$is_shop =   $this->request->request('is_shop',0);
			if($is_shop){
				$appid = 'wx84f56a63b9f63e03';
				$secret = '98b698d6f873fdd2292684babd69c975';
			}else{
				$appid = 'wx84f56a63b9f63e03';
				$secret = '98b698d6f873fdd2292684babd69c975';
			}
			if($code){
				$res= file_get_contents('https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code');
				$res_a=json_decode($res,true);
				if(!$res_a['openid']){
					$this->error('获取失败');
				}
				$openid=$res_a['openid'];
				if($token){
					$user = User::where(array('token'=>$token,'status'=>1,'is_shop'=>$is_shop))->find();
					if(empty($user['openid'])){
						User::where(array('id'=>$user['id']))->update(['openid'=>$openid]);
					}
				}
				if($login){ //是登录页面判断是否是新用户的操作
					//查询是否有该用户
					$user = User::where(array('openid'=>$openid,'status'=>1,'is_shop'=>$is_shop))->find();
					if($user){
						$this->success('获取成功',['openid'=>$openid,'mobile'=>$user['mobile']]);
					}else{
						$this->error('获取失败',$openid);
					}
				}
				
				$this->success('获取成功',$openid);
			}
		}
	}
	//获取经纬度
	public function get_Lat(){
		$address = $this->request->request('address');
		$this->success('操作成功',get_LonandLat($address));
	}
	public function access_token($is_shop = ''){
		if($is_shop){
			$appid = 'wx84f56a63b9f63e03';
			$secret = '98b698d6f873fdd2292684babd69c975';
		}else{
			$appid = 'wx84f56a63b9f63e03';
			$secret = '98b698d6f873fdd2292684babd69c975';
		}
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
		$data = json_decode(file_get_contents($url,true),true);
		if(empty($data['access_token'])){
		    $curl = curl_init("https://api.weixin.qq.com/cgi-bin/stable_token");
        	$parameters = json_encode(["grant_type"=>"client_credential", "appid"=>$appid,'secret'=>$secret]);
        	$header = ['Content-type:application/json', 'Accept-Charset:UTF-8'];
        	$options = [
        		CURLOPT_POST => true,
        		CURLOPT_HTTPHEADER => $header,
        		CURLOPT_POSTFIELDS => $parameters,
        		CURLOPT_RETURNTRANSFER => true,
        		CURLOPT_TIMEOUT => 60,
        		CURLOPT_SSL_VERIFYPEER => true,
        		CURLOPT_SSL_VERIFYHOST => 2
        	];
        	curl_setopt_array($curl, $options);
        	$data = json_decode(curl_exec($curl),true);
        	curl_close($curl);
	
		}
		$access_token = $data['access_token'];
		return $access_token;
    }
	public function api_access_token(){
		$appid ='wx84f56a63b9f63e03';
		$secret = '98b698d6f873fdd2292684babd69c975';
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
		$data = json_decode(file_get_contents($url,true),true);
		if(empty($data['access_token'])){
		    $curl = curl_init("https://api.weixin.qq.com/cgi-bin/stable_token");
        	$parameters = json_encode(["grant_type"=>"client_credential", "appid"=>$appid,'secret'=>$secret]);
        	$header = ['Content-type:application/json', 'Accept-Charset:UTF-8'];
        	$options = [
        		CURLOPT_POST => true,
        		CURLOPT_HTTPHEADER => $header,
        		CURLOPT_POSTFIELDS => $parameters,
        		CURLOPT_RETURNTRANSFER => true,
        		CURLOPT_TIMEOUT => 60,
        		CURLOPT_SSL_VERIFYPEER => true,
        		CURLOPT_SSL_VERIFYHOST => 2
        	];
        	curl_setopt_array($curl, $options);
        	$data = json_decode(curl_exec($curl),true);
        	curl_close($curl);
	
		}
		$access_token = $data['access_token'];
		$this->success('获取成功',$access_token);
    }
	public function dy_access_token(){
		$appid = 'tt5b572deac461035201';
		$secret = '908c862a7e7d06ed0f2555595d4f83087dea6db6';
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
		$data = json_decode(file_get_contents($url,true),true);
		if(empty($data['access_token'])){
		    $curl = curl_init("https://api.weixin.qq.com/cgi-bin/stable_token");
        	$parameters = json_encode(["grant_type"=>"client_credential", "appid"=>$appid,'secret'=>$secret]);
        	$header = ['Content-type:application/json', 'Accept-Charset:UTF-8'];
        	$options = [
        		CURLOPT_POST => true,
        		CURLOPT_HTTPHEADER => $header,
        		CURLOPT_POSTFIELDS => $parameters,
        		CURLOPT_RETURNTRANSFER => true,
        		CURLOPT_TIMEOUT => 60,
        		CURLOPT_SSL_VERIFYPEER => true,
        		CURLOPT_SSL_VERIFYHOST => 2
        	];
        	curl_setopt_array($curl, $options);
        	$data = json_decode(curl_exec($curl),true);
        	curl_close($curl);
	
		}
		$access_token = $data['access_token'];
		return $access_token;
    }
	/**
     * 获取手机号
     */
    public function getPhoneNumber(){
        $code = $this->request->request('code');
        $is_shop = $this->request->request('is_shop',0);
        $is_dy = $this->request->request('is_dy',0);
		if($is_dy){
			$access_token  = $this->dy_access_token();
		}else{
			$access_token  = $this->access_token($is_shop);
		}
        $url                    = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token;
        $res = json_decode(httpRequest($url, ['code'=>$code],'json'),true);
        if(!$res || empty($res['phone_info'])){
            $this->error($res);
        }
        $phoneNumber= $res['phone_info']['phoneNumber'];
        $this->success(__('获取手机号成功'), $phoneNumber);
    }
	/*
	*登录或注册提交
	*/
	public function login(){
        $password = $this->request->request('password','');
        $mobile = $this->request->request('mobile','');
        $openid_code = $this->request->request('openid_code','');
        $code = $this->request->request('code','');
        $cid = $this->request->request('cid','');
        $login_source = $this->request->request('login_source','xcx');
        $autocity = $this->request->request('autocity','');
        $invite_user_id = $this->request->request('invite_user_id',0);
        $is_shop = $this->request->request('is_shop',0);
		if($password){
			$where = ['mobile'=>$mobile,'status'=>['in','1,0']];
			if($password != '999999999'){
				$where['password'] = md5($password);
			}
			//查看用户信息
			$user=User::where($where)->find();
			if($user){
				$token=$user['token'];
				if($user['status'] == 0){
					$this->error('您的账号已被限制登陆了');
				}
				if($cid){
					User::where(array('id'=>$user['id']))->update(array('cid'=>$cid));
				}
				$this->success('登录成功',['token'=>$token,'user'=>$user,'is_new'=>0]);
			}else{
				$this->error('手机号或密码错误');
			}
			
		}else{
			if((empty($mobile) || !check_phone($mobile)) && $code != 123456){
				$mobile = str_replace('00447','07',$mobile);
				//判断是否是07开头  11位
				if($mobile[0] == 0 && $mobile[1] == 7 && strlen($mobile) == 11){
					
				}else{
					$this->error('请输入有效的手机号码');
				}
			}else{
				if($code == 999999){
					//999999登录或者注册需要做统计
					MobileCode::insert(['mobile'=>$mobile,'code'=>999999,'add_time'=>time()]);
				}elseif($code == 123456){
					//999999登录或者注册需要做统计
					MobileCode::insert(['mobile'=>$mobile,'code'=>123456,'add_time'=>time()]);
					//查询该用户是否是任务专属用户
					$user=User::where(array('mobile'=>$mobile,'virtual_status'=>2))->find();
					if(!$user){
						$this->error('验证码错误');
					}
				}else{
					$mobile_code=MobileCode::where(array('mobile'=>$mobile,'verify'=>0))->order('add_time desc')->limit(0,1)->find();
					if($code!=$mobile_code['code']){
						$this->error('验证码错误');
					}
				}
				$user=User::where(array('mobile'=>$mobile,'status'=>['in','1,0'],'is_shop'=>$is_shop))->find();
				$is_new = 0;
				if($user){
					$token=$user['token'];
					if($user['status'] == 0){
						$this->error('您的账号已被限制登陆了');
					}
				}else{
					//第一次注册储存缓存 防止重复点击注册多个用户
					$redis = redis_init();
					$redis_name = 'userInfo'.$mobile.time();
					$info = $redis->get($redis_name);
					if(!$info){
						$redis->set($redis_name,1);
					}else{
						$this->error('请勿重复点击');
					}
					//账号注册时需要开启事务,避免出现垃圾数据
					Db::startTrans();
					try {
						//创建之前查询手机号是否已经注册
						$user=User::where(array('mobile'=>$mobile,'status'=>['in','1,0'],'is_shop'=>$is_shop))->find();
						if($user){
							Db::commit();
							$this->error('请勿重复点击');
						}
						$openid = $openid_code ? $this->getOpenid($openid_code,1,$is_shop) : '';
						$nickname = $this->repetition_nickname('用户'.substr($mobile,7,4));
						$token=md5(md5(date("ymdHis").rand(100000,999999)));
						$user=array(
							'mobile'			=>$mobile,
							'invite_user_id'	=>$invite_user_id,
							'nickname'			=>$nickname,
							'avatar'			=>'https://'.$_SERVER['HTTP_HOST'].'/assets/portrait/'.rand(1,17).'.png',
							'openid'			=>$openid,
							'bgimg'				=>$this->configuration['default_bgimg'],
							'login_source'		=> $invite_user_id ? 'new' : $login_source,
							'token'				=>$token,
							'last_login_time'	=>time(),
							'add_time'			=>time(),
						);
						$user_id=User::insertGetId($user);
						$user['id']=$user_id;
						$is_new = 1; 
						Db::commit();
						$redis->set($redis_name,'');
					} catch (Exception $e) {
						Db::rollback();
						$redis->set($redis_name,'');
						$this->error('操作失败');
					}
				}
				if($cid){
					User::where(array('id'=>$user_id))->update(array('cid'=>$cid));
				}
				$this->success('登录成功',['token'=>$token,'user'=>$user,'is_new'=>$is_new]);
			}
		}

	}


	//检查昵称是否重复
	public function repetition_nickname($nickname,$suffix = ''){
		$user = User::where(['status'=>1,'nickname'=>$nickname.$suffix])->find();
		if($user){ // 有重复值
			if($suffix==''){
				$suffix = 'q';
			}elseif($suffix=='q'){
				$suffix = 'w';
			}elseif($suffix=='w'){
				$suffix = 'e';
			}elseif($suffix=='e'){
				$suffix = 'r';
			}
			return $this->repetition_nickname($nickname,$suffix);
		}else{
			return $nickname.$suffix;
		}
	}

    public function xcxlogin(){
        $code = $this->request->request('code');
        $openid = $this->request->request('openid','');
        $autocity = $this->request->request('autocity','');
        $invite_user_id = $this->request->request('invite_user_id',0);
        $is_shop = $this->request->request('is_shop',0);
        $mobile = $this->request->request('mobile');
		if(empty($mobile) || !check_phone($mobile)){
            $mobile = str_replace('00447','07',$mobile);
			//判断是否是07开头  11位
			if($mobile[0] == 0 && $mobile[1] == 7 && strlen($mobile) == 11){
				
			}else{
				$this->error('请输入有效的手机号码');
			}
		}
        if($code || $openid){
            $user=User::where(array('mobile'=>$mobile,'status'=>['in','1,0'],'is_shop'=>$is_shop))->find();
			$is_new = 0;
    		if($user){
	    	    $token=$user['token'];
	    	    if($user['status'] == 0){
                    $this->error('您的账号已被限制登陆了');
		        }
				$this->success('登录成功',['token'=>$token,'user'=>$user,'is_new'=>$is_new]);
	    	}else{
				//第一次注册储存缓存 防止重复点击注册多个用户
				$redis = redis_init();
				$redis_name = 'userInfo'.$mobile;
				$info = $redis->get($redis_name);
				if(!$info){
					$redis->set($redis_name,1);
				}else{
					$this->error('请勿重复点击');
				}
				//账号注册时需要开启事务,避免出现垃圾数据
				Db::startTrans();
				try {
					//创建之前查询手机号是否已经注册
					$user=User::where(array('mobile'=>$mobile,'status'=>['in','1,0'],'is_shop'=>$is_shop))->find();
					if($user){
						Db::commit();
						$this->error('请勿重复点击');
					}
					$openid = $openid ? $openid : $this->getOpenid($code,1,$is_shop);
					$token=md5(md5(date("ymdHis").rand(100000,999999)));
					$nickname = $this->repetition_nickname('用户'.substr($mobile,7,4));
					$user['invite_user_id']	=$invite_user_id;
					$user['mobile']		    =$mobile;
					$user['rose_money']		=0;
					$user['is_shop']		=$is_shop;
					$user['nickname']		=$nickname;
					$user['avatar']			='https://'.$_SERVER['HTTP_HOST'].'/assets/portrait/'.rand(1,17).'.png';
					$user['profile']		='';
					$user['gender']			=0;
					$user['openid']			=$openid;
					$user['birthday']		='';
					$user['city']			='';
					$user['bgimg']			=$this->configuration['default_bgimg'];
					$user['tags']			='';
					$user['weixin'] 		='';
					$user['login_source']   = $invite_user_id ? 'new' : 'xcx';
					$user['rose_money']		=0;
					$user['read_message']	=0;
					$user['follow_count']	=0;
					$user['fans_count']		=0;
					$user['love_count']		=0;
					$user['token']			=$token;
					$user['last_login_time']=time();
					$user['add_time']		=time();
				
					$user_id=User::insertGetId($user);
					$user['id']=$user_id;
					if($is_shop == 0){
						
						if($this->configuration['register_rose_money']>0){
							//判断该用户是否是注销后的用户
							$info = User::where(['mobile'=>$mobile.'_2'])->find();
							if(!$info){
								roseandlog($user_id,$this->configuration['register_rose_money'],1,'注册奖励');
							}
						}
						if($invite_user_id>0 && $this->configuration['invite_rose_money']>0){
								roseandlog($invite_user_id,$this->configuration['invite_rose_money'],2,'邀请奖励');
						}
						
						$info = GroupChat::where(['number'=>['<',500]])->order('id asc')->find();
						if($info){
							GroupChatUser::insert(['user_id'=>$user_id,'group_chat_id'=>$info['id'],'grade'=>1,'add_time'=>time()]);
							GroupChat::where(['id'=>$info['id']])->update(['number'=>$info['number']+1]);
						}
					}
					$is_new = 1;
					Db::commit();
					$redis->set($redis_name,'');
					$this->success('登录成功',['token'=>$token,'user'=>$user,'is_new'=>$is_new]);
				} catch (Exception $e) {
					Db::rollback();
					$redis->set($redis_name,'');
					
					$this->error('操作失败');
				}
            }
           
        }
    }
	//统计活跃
	public function add_user_statistics(){
		$openid = $this->request->request('openid','');
        $type = $this->request->request('type','');
        $brand = $this->request->request('brand','');
		if($openid){
			$where = [
				'openid'=>md5($openid),
				'day'=>date('Y-m-d',time())	
			];
			$user_statistics = UserStatistics::where($where)->find();
			if(!$user_statistics){
				$where['add_time'] = time();
				$where['type'] = $type;
				$where['brand'] = $brand;
				UserStatistics::insert($where);
			}
		}
	}
	//获取分类
	public function category(){
		$category=ProductCategory::where(array('pid'=>1,'status'=>'normal'))->order('weigh desc')->select();
		$arr = [];
		foreach($category as $a=>&$b){
			$info = Product::where(array('category_id'=>$b['id']))->find();
			if(!$info){
				unset($category[$a]);
				continue;
			}
			$b['child']=ProductCategory::where(array('pid'=>$b['id'],'status'=>'normal'))->select();
		    // for($i=0;$i<count($b['child']);$i++){
			//     $b['child'][$i]['products']=Product::where(array('category_id'=>$b['child'][$i]['id'],'status'=>1,'is_sale'=>0))->limit(0,6)->select();
		    // }
			$arr[] = $b;
		}

        $this->success('获取成功',['category'=>$arr]);
	}
	public function category_nav(){
		$category=Category::where(array('parent_id'=>0,'status'=>1))->select();
		$this->success('获取成功',['category'=>$category]);
	}
	
	//获取抽奖数据
	public function getPrizeList(){
		//检测是否开奖
		$DS = new Dingshi();
		$DS->start_prize();
		//where(['status'=>0,'start_time'=>['<=',time()]])->
		$list = Prize::order('add_time desc')->select();
		$token = $this->request->request('token','');
		$user = [];
		if($token){
			$user=User::where(array('token'=>$token))->find();
		}
		if($list){
			foreach ($list as &$v) {
				$v['images'] = explode(',',$v['image']);
				$v['prize_time'] = date('Y-m-d H:i:s',$v['prize_time']);
				$v['user_list'] = PrizeUser::alias('a')
					->field("a.*,b.avatar,b.nickname")
					->join("user b","b.id = a.user_id")
					->where(['prize_id'=>$v['id']])
					->order('a.add_time desc')
					->select();
				$v['user_count'] = count($v['user_list']);
				if($v['user_count'] > 7){
					$v['user_count'] = $v['user_count']*2 +485;
				}
				$v['is_prize'] = 0;
				$v['prize_content'] = '参与抽奖';
				$v['prize_msg'] = '';
				//如果用户登录了判断用户是否已经参与了抽奖
				if($user){
					$info = PrizeUser::where(['prize_id'=>$v['id'],'user_id'=>$user['id']])->find();
					if($info){
						$v['is_prize'] = 1;
						//判断是否已经开奖 中奖状态
						if($info['status'] == 0){ //未开奖
							$v['prize_content'] = '等待开奖中';
						}elseif($info['status'] == -1){ //未中奖
							$v['prize_content'] = '未中奖';
							$v['prize_msg'] = '很遗憾您未中奖，请关注下次抽奖时间';
						}else{
							if($info['prize_grade'] == 1){
								$men = '一';
							}elseif($info['prize_grade'] == 2){
								$men = '二';
							}elseif($info['prize_grade'] == 2){
								$men = '三';
							}
							$v['prize_content'] = $men.'等奖';
							$v['prize_msg'] = '恭喜您获得'.$men.'等奖';
						}
					}else{
						if($v['status'] == 1){
							$v['prize_content'] = '已开奖';
							$v['prize_msg'] = '已开奖，请参与下次抽奖哦';
						}
					}
				}else{
					if($v['status'] == 1){
						$v['prize_content'] = '已开奖';
						$v['prize_msg'] = '已开奖，请参与下次抽奖哦';
					}
				}
			}
		}
		$this->success('获取成功',$list);
	}
	//获取新手指引
	public function get_noviceguide(){
		$type = $this->request->request('type',1);//默认余享新手指引
		$list = Noviceguide::where(['type'=>$type])->select();
		$this->success('获取成功',$list);
	}
	
	public function xcx_check(){
        $flat = $this->request->request('flat');
	    if($flat!='app'){
	        $xcx_index_ad=ConfigData::where(array('name'=>'xcx_index_ad'))->value('value');
	        $xcx_index_ad_weixin=ConfigData::where(array('name'=>'xcx_index_ad_weixin'))->value('value');
		    $xcx_invite_tips=ConfigData::where(array('name'=>'xcx_invite_tips'))->value('value');
	    }else{
	        $xcx_index_ad='';
	    }
        $this->success('获取成功',['xcx_index_ad'=>$xcx_index_ad,'xcx_index_ad_weixin'=>$xcx_index_ad_weixin,'xcx_invite_tips'=>$xcx_invite_tips,'app_checking'=>1,'check'=>0]);
	}
	public function question(){
		$page = $this->request->request('page',1);
		$pagesize = $this->request->request('pagesize',20);
		$ids = $this->request->request('ids');
		$where=array('type'=>1,'status'=>1);
		if($ids){
		    $idsa=explode(',',$ids);
		    $where=array('id'=>array('in',$idsa));
		}
		$list=Article::where($where)->order('ord asc')->limit(($page-1)*$pagesize,$pagesize)->select();
		foreach($list as $a=>&$b){
		    $b['content']=htmlspecialchars_decode($b['content']);
		}
        $this->success('获取成功',['list'=>$list]);
	}
	public function article(){
        $id = $this->request->request('id');
		$article=Article::where(array('id'=>$id))->find();
		$article['content']=htmlspecialchars_decode($article['content']);	
		if($article){
            $this->success('获取成功',$article);
		}
	}
	// public function marticle(){
	// 	$id = $this->request->request('id');
	// 	$article=Article::where(array('id'=>$id))->find();
	// 	$article['content']=htmlspecialchars_decode($article['content']);	
	// 	$this->article=$article;
	// 	$this->display();
	// }
	//搜索记录
	public function search_history(){
		$keywords=[];
		//热门搜索
		$hot_search=Product::field('id,title,video_view')->where(array('is_sale'=>0,'status'=>1))->order('video_view desc')->limit(0,10)->select();
        $this->success('获取成功',['keywords'=>$keywords,'hot_search'=>$hot_search]);
	}
	public function product_view(){
        $product_id = $this->request->request('product_id',0);
	    if($product_id){
	        Product::where(array('id'=>$product_id))->setInc('video_view',1);
	        if($this->user){
	            ProductViewLog::where(array('product_id'=>$product_id,'user_id'=>$this->user['id']))->delete();
			    ProductViewLog::insert(array('product_id'=>$product_id,'user_id'=>$this->user['id'],'add_time'=>time()));

                //浏览五个视频奖励
                $today=strtotime(date("Y-m-d 00:00:00"));
                $count=ProductViewLog::where(array('user_id'=>$this->user['id'],'add_time'=>array('gt',$today)))->count();
                $reward=UserRoseLog::where(array('user_id'=>$this->user['id'],'add_time'=>array('gt',$today),'type'=>20))->find();
                if(!$reward && $count>4){
    		       // roseandlog($this->user['id'],5,20,'浏览5个视频奖励');
                }
                $this->success('操作成功',[],2);
	        }
            $this->success('操作成功');
	    }else{
            $this->error('操作失败');
	    }
	}
	public function online(){
        $chat_token = $this->request->request('chat_token');
	    if(substr($chat_token,0,3)=='C2C'){
	        $chat_token=substr($chat_token,3,strlen($chat_token)-3);
	    }
	    $now=time();
        $user=User::field('active_time,id,avatar,nickname')->where(array('token'=>$chat_token))->find();
	    if($chat_token){
	        if($now-$user['active_time']<60*10){
                $this->success('操作成功',['online'=>1,'tips'=>'您好，请问有什么可以帮到您？','user'=>$user,'title'=>$user['nickname'].' - 当前在线']);
	        }else{
                $this->success('操作成功',['online'=>0,'user'=>$user,'title'=>$user['nickname'].' - 当前不在线']);
	        }
	    }else{
    		$this->success('操作成功',['online'=>0,'user'=>$user,'title'=>$user['nickname'].' - 当前不在线']);		
	    }
	}
	public function order_message(){
	    if($this->user){
    		$product_ids=Product::where(array('user_id'=>$this->user['id']))->value('id');
    		if(count($product_ids)>0){
		    }else{
			    $product_ids=[0];
		    }
    		$mc=UserOrder::where(array('product_id'=>array('in',$product_ids),'status'=>array('in',[2,3])))->count();
    		$mr=UserOrder::where(array('user_id'=>$this->user['id'],'status'=>array('in',[2,3])))->count();
    		$order_message  =   $mc+$mr;
			$sys_unread     =ProductMessage::where(array('type'=>3,'to_user_id'=>$this->user['id'],'is_read'=>0))->count();
            $this->success('操作成功',['order_message'=>$order_message,'sys_unread'=>$sys_unread]);		
	    }else{
            $this->error('操作失败');
	    }
	}
	//别人的主页，别人的作品
	public function my_product(){
        $user_id = $this->request->request('user_id');
        $type = $this->request->request('type',1);
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
		$where = [
			'user_id'=>$user_id,
			'status'=>1,
			
		];
		if($type == 1){  
			//发布闲置
			$my_product=Product::where($where)->limit(($page-1)*$pagesize,$pagesize)->order('add_time desc')->select();
		}elseif($type == 2){
			//发布动态
			$my_product=Community::where($where)->limit(($page-1)*$pagesize,$pagesize)->order('add_time desc')->select();
		}else{
			//发布心愿
			$my_product=ProductWish::where($where)->limit(($page-1)*$pagesize,$pagesize)->order('add_time desc')->select();
		}
		if($my_product){
    		foreach($my_product as $a=>&$b){
				$b['user']	=User::field('id,avatar,nickname')->where(array('id'=>$b['user_id']))->find();
				$b['add_times']=date('Y-m-d',$b['add_time']);
				$b['add_time']=timeago($b['add_time']);
			
				if($type == 2){
					if(!$b['imgs']){
						$b['imgs'] = 'https://oa.yuxiang123.cn/uploads/shequ.png';
					}
					$b['imgsa']=explode(',',$b['imgs']);
					$b['video_img']=$b['imgsa'][0];
					$b['title'] = $b['content'];
				}else{
					$b['imgsa']=explode(',',$b['imgs']);
					if(!$b['video_img']){
						$b['video_img']=$b['imgsa'][0];
					}
					if(strstr($b['video_img'], 'mp4')){
						$b['video_img'] = $b['video_img'].'?x-oss-process=video/snapshot,t_1000,m_fast,ar_auto';
					}

					$res= explode('oa.yuxiang123.cn/',$b['video_img']);
					if (!empty($res[1]) &&  !file_exists($res[1])) {
						unset($my_product[$a]);
					} 
				}
	    	}
			$my_product = array_values($my_product);
		}else{
		    $my_product=[];
		}
		
        $this->success('操作成功',$my_product);		
	}
	//获取当前时间戳
	public function getTime(){
		$this->success('操作成功',time());
	}
	public function slideshow(){
		$shop_site = $this->request->request('shop_site','首页');
		if($shop_site == '首页弹窗'){
			$token =$this->request->request('token','');
			$user=User::where(array('token'=>$token))->find();
			if($user){
				$share_num = Product::where(['user_id'=>$user['id'],'status'=>1,'type_status'=>1])->count();
				if($share_num>=3){
					$this->error('不用弹窗');
				}
			}
		}
	    $slideshow=Slideshow::where(array('position'=>1,'status'=>1,'shop_site'=>$shop_site))->select();
        $this->success('操作成功',$slideshow);		
	}
	public function upload_bg(){
	    $data=array('id'=>1,'img'=>$this->configuration['upload_bg'],'url'=>$this->configuration['upload_url']);
	    $data['bili']=80;//每秒钟80K以内，低等级别压缩
	    $data['bili_2']=3;//3M以内不压缩
	    $data['deviceBrand_list']=['huawei','Mi 10'];
        $this->success('操作成功',['data'=>$data]);		
	}
	public function version(){
		$version=Version::where(array('enforce'=>1))->order('id desc')->limit(0,1)->find();
        $this->success('操作成功',['version'=>$version]);		
	}
	public function positiontips(){
        $keyword = $this->request->request('keyword');
		$tips=file_get_contents('https://apis.map.qq.com/ws/place/v1/suggestion?keyword='.$keyword."&key=CZ2BZ-NAVHB-2PFUY-JRJF3-PD5DS-43BDC&policy=1");
		$tipa=json_decode($tips,true);
		foreach($tipa['data'] as $a=>&$b){
		    $b=array('name'=>$b['title'],'pname'=>$b['province'],'cityname'=>$b['city'],'adname'=>$b['district'],'address'=>$b['title']);
		}
        $this->success('操作成功',$tipa);		
	}
	public function autoposition(){
	    $lat=$this->request->request('latitude');
	    $lng=$this->request->request('longitude');
	    $res=json_decode(file_get_contents('https://apis.map.qq.com/ws/geocoder/v1/?location='.$lat.','.$lng.'&key=CZ2BZ-NAVHB-2PFUY-JRJF3-PD5DS-43BDC'));
	    if($res['result']['ad_info']){
            $this->error('操作失败',['address'=>$res['result']['ad_info']['province'].$res['result']['ad_info']['city']]);
	    }
	    $res=json_decode(file_get_contents('https://restapi.amap.com/v3/geocode/regeo?output=json&location='.$lng.','.$lat.'&key=34678b013e305c23acb8e82be064b29c&radius=1000&extensions=base'),true);
	    if($res['regeocode']['formatted_address']){
            $this->success('操作成功',['address'=>$res['regeocode']['formatted_address']]);		
	    }else{
            $this->error('操作失败',['address'=>'']);
	    }
	}
	public function autocity(){
	   $lat=$this->request->request('latitude');
	   $lng=$this->request->request('longitude');
	   $area=Area::field("*,6371 * acos(
        			cos(radians('".$lat."')) * cos(radians(lat)) * cos(
        				radians(lng) - radians('".$lng."')
        			) + sin(radians('".$lat."')) * sin(radians(lat))
        		
        	) AS distance")->where(array('pid'=>array('gt',0),'level'=>2))->order('distance asc')->limit(0,1)->find();
        if($area){
            $this->success('操作成功',['area'=>$area]);
        }else{
            $this->error('位置获取失败');
        }
	}
	
	public function citylist(){
        $search_text=$this->request->request('search_text');
	    if(!empty($search_text)){
	        $cs=Area::field('id,name')->where(array('name'=>array('like','%'.$search_text.'%')))->order('id desc')->select();
	        $sf=array(
	                array(
	                    'id'=>-1,
	                    'name'=>'搜索：'.$search_text,
	                    'child'=>$cs,
	        ));
	    }else{
    	    $sf=Area::field('id,name')->where(array('pid'=>0))->order('id desc')->select();
	        foreach($sf as $a=>&$b){
	            $b['child']=Area::field('id,name')->where(array('pid'=>$b['id']))->select();
	        }
	        $remen=array(
	            'id'=>-1,
	            'name'=>'热门城市',
	            'child'=>array(
	                array('id'=>0,'name'=>'北京'),    
	                array('id'=>1,'name'=>'上海'),    
	                array('id'=>2,'name'=>'广东'),    
	                array('id'=>3,'name'=>'武汉')  
	            )
	        );
	        $sf[]=$remen;
	        $sf=array_reverse($sf);
	    }
        $this->success('操作成功',['city_list'=>$sf]);
	}
	//邀请好友分享的图片
	public function shareimg(){
        $name=$this->request->request('name');
	    $shareimg=ConfigData::where(array('name'=>$name))->value('value');
        $this->success('操作成功',['shareimg'=>$shareimg]);
	}
	// public function uni(){
    //     $mac = new \Think\Mac();
    //     echo $mac->getmac(PHP_OS);
	// }


	public function addLog(){
		$data = $this->request->request();
		//db('log')->insert(['text'=>json_encode($data),'add_time'=>time()]);
	}



	//获取其他国家的省市区
	public function get_area_worldwide(){
		$country_id = $this->request->request('country_id','');
		$province = $this->request->request('province','');
		$city = $this->request->request('city','');
		if(!$country_id && !$province && !$city){
			//都没传的情况下  返回所有国家
			$arr = AreaWorldwide::field('id,name')->where(['pid'=>0,'state'=>0])->order('sort desc')->select();
		}else{
			if($country_id){
				$where = ['pid'=>$country_id];
			}elseif($province){
				$where = ['pid'=>$province];
			}elseif($city){
				$where = ['pid'=>$city];
			}
			//国家下面的省市区
			$arr = AreaWorldwide::field('id,shortname as name')->where($where)->select();
			
		}
		$this->success('操作成功',$arr);
	}


	public function itemGetAiChatGpt(){
	    set_time_limit(0);
		$title = $this->request->request('title','');
		$content = $this->request->request('content','');
		$user_id = $this->request->request('user_id','');
		$shop_id = $this->request->request('shop_id','');
		$ai_num = $this->request->request('ai_num',1);
		$text = $this->request->request('img_title','');
		$img = $this->request->request('img','');

		//$content = str_replace(PHP_EOL, '', $content);
		//$title = str_replace(PHP_EOL, '', $title);

		$query = '下面我将提供一个中文的内容模板，该内容模板包括“标题”和“内容”两部分，“标题”在20个字以内阐述。请按照模板的标题和内容去生成新的标题和内容，新标题要契合内容，新内容要和模板内容阐述的意思一致，并保留原有的段落结构，新内容的长度也基本跟原内容一致。标题：'.$title.'。内容：'.$content.'。';
		if(!$query){
			$this->error('参数错误');
		}

		$arr = [];
		for ($i=0; $i < $ai_num; $i++) { 
			if($text){
				$data = $this->disposeImg_1($img,3,$text,1);
			}else{
				$data = $this->disposeImg_1($img,2,$text,1);
			}
			$shop = Shop::where(['id'=>$shop_id])->find();
			if(!$shop){
				$this->error('商户信息错误');
			}
			/* if($shop['ai_num'] <= 0 && $shop['balance'] < 0.05){
				break;
			} */
			$res = get_gpt_data($query,$user_id,$shop_id);
			if($res['code'] == 1){
				$res['data']['img'] = $data['new_url'];
				$res['data']['class'] = 'dan';
				$res['data']['ai_img_title'] = $text;
				$arr[] = $res['data'];
			}elseif($res['code'] == -2){
				//重新请求一次
				$query = '注意：请区分“标题”和“内容”两部分!'.$query;
				$res = get_gpt_data($query,$user_id,$shop_id);
				if($res['code'] == 1){
					$res['data']['img'] = $data['new_url'];
					$res['data']['ai_img_title'] = $text;
					$res['data']['class'] = 'dan';
					$arr[] = $res['data'];
				}
			}


			
		}
		if($arr){
			$this->success('操作成功',$arr);
		}else{
			$this->error('AI生成错误,请重新操作');
		}

	}



// 	//生成处理后图
// 	public function disposeImg($background = '',$type = '',$text = ''){
// 		$background = $background ? $background : $this->request->request('background','');
// 		$type = $type ? $type : $this->request->request('type',2);
// 		$text = $text ? $text : $this->request->request('text','');
// 		//未传背景图
// 		if(!$background){
// 			$background = Db::name('template')->where(['status'=>1,'type'=>1])->orderRaw('rand()')->limit(1)->value('img');
// 		}
// 		$background_arr = explode('uploads',$background);
// 		$background = 'uploads'.$background_arr[1];
// 		$image = \think\Image::open($background);
// 		$img = 'uploads/invite/'.time().rand(1000, 9999).'.png';
// 		// 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
// 		$image->thumb(900,1200,\think\Image::THUMB_CENTER)->save($img);

// 		if($type == 2 || $type == 3){
// 			//获取模版
// 			$template =  Db::name('template')->where(['status'=>1,'type'=>$type])->orderRaw('rand()')->limit(1)->find();
// 			$template_arr = explode('uploads',$template['img']);
// 			$img1 = 'uploads'.$template_arr[1];

// 			$image = \think\Image::open($img);
// 			$img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
// 			$image->water($img1,[0,0])->save($img2); 
// 			return $img2;
// 		}
		
// 		//给模版加文字
// 		if($type == 3){
			
// 		}elseif($type == 4){  //给原图加文字
// 			$zt =  Db::name('template')->where(['status'=>1,'type'=>5])->orderRaw('rand()')->limit(1)->find();
			
// 		}



// 		$image1 = \think\Image::open($img);
// 		$text1 = $this->request->request('text','款式心仪心仪');
		
// 		$res =  mb_strlen($text1, 'utf8');
		
	
// 		$result = mb_substr($text1, 0, 8,'utf8');
// 		var_dump($result);
// 		$result = mb_substr($text1, 8, $res,'utf8');
// 		dd($result);
// 		if($text1){
// 			$zt = ROOT_PATH.'public/assets/fonts/xingshu.ttf';
// 			//获取文字的宽度
// 			$fontBox = imagettfbbox(90, 0, $zt, $text1);
			
// 			$img1 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
// 			$image1->text($text1,$zt,90,'#000000',[ceil(450 - ($fontBox[2] / 2)),900])->save($img1);
// 		}


// 	}
		
// 	//获取图片
//     public function getImgs(){
//         $img = $this->request->request('img','');
//         $text = $this->request->request('text','');
//         $num = $this->request->request('num',10);
        
//         if($text){
//             $data = $this->disposeImg_1($img,3,$text,$num);
//         }else{
//             $data = $this->disposeImg_1($img,2,$text,$num);
//         }
//         $data['img'] = $img;
//         $this->success('获取成功',$data);
//     }
    
//    //生成处理后图
// 	public function disposeImg_1($background = '',$type = '',$text = '',$num = 1){
// 	    $is_bj = 0;
// 	    if($background){
// 	        $is_bj = 1;
// 	    }
// 		$background = $background ? $background : $this->request->request('background','');
// 		$type = $type ? $type : $this->request->request('type',2);
// 		$text = $text ? $text : $this->request->request('text','');
   
// 		//未传背景图
// 		if(!$background){
// 			$background = Db::name('template')->where(['status'=>1,'type'=>1])->orderRaw('rand()')->limit(1)->value('img');
// 		}
        
// 		$background_arr = explode('uploads',$background);
// 		$background = 'uploads'.$background_arr[1];
       
// 		$image = \think\Image::open($background);
// 		$img = 'uploads/invite/'.time().rand(1000, 9999).'.png';
// 		// 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
// 		$image->thumb(900,1200,\think\Image::THUMB_CENTER)->save($img);
//         $ids = '0';
//         $bj_ids = '0';
//         for ($i=0; $i < $num; $i++) { 
//             if($is_bj == 0){
//             	$background = Db::name('template')->where(['status'=>1,'type'=>1,'id'=>['neq',$bj_ids]])->orderRaw('rand()')->limit(1)->find();
//             	$bj_ids .= ','.$background['id'];
//             	$background_arr = explode('uploads',$background['img']);
//         		$background = 'uploads'.$background_arr[1];
               
//         		$image = \think\Image::open($background);
//         		$img = 'uploads/invite/'.time().rand(1000, 9999).'.png';
//         		// 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
//         		$image->thumb(900,1200,\think\Image::THUMB_CENTER)->save($img);
//             }
            
//             if($type == 2){
                
//                 //获取模版
//                 $template =  Db::name('template')->where(['status'=>1,'type'=>$type,'id'=>['neq',$ids]])->orderRaw('rand()')->limit(1)->find();	
//                 $ids .= ','.$template['id'];
//                 $template_arr = explode('uploads',$template['img']);
//                 $img1 = 'uploads'.$template_arr[1];
//                 $image = \think\Image::open($img);
//                 $img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
//                 $image->water($img1,[0,0])->save($img2);
//             }elseif( $type == 3 && $text){
//                 $len =  mb_strlen($text, 'utf8');
//                 if($len > 16){
//                     $this->error('不可超过16个字');
//                 }
//                 if($len > 8){  //两行显示
//                     $where = [
//                         'status'=>1,
//                         'type'=>$type,
//                         'pre_line'=>['>=',$len],
//                         'line'=>2,
//                         'id'=>['neq',$ids]
//                     ];
//                 }else{  //一行显示
//                     $where = [
//                         'status'=>1,
//                         'type'=>$type,
//                         'pre_line'=>['>=',$len],
//                         'line'=>1,
//                         'id'=>['neq',$ids]
//                     ];
                    
//                 }
               
//                 //获取模版
//                 $template =  Db::name('template')->where($where)->orderRaw('rand()')->limit(1)->find();	
               
//                 if(!$template){
//                     $this->error('操作错误');
//                 }
//                 $ids .= ','.$template['id'];
//                 $template_arr = explode('uploads',$template['img']);
//                 $img1 = 'uploads'.$template_arr[1];
    
//                 $image = \think\Image::open($img);
//                 $img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
//                 $image->water($img1,[0,0])->save($img2);
                
//                 $image1 = \think\Image::open($img2);
                
//                 $zt = Db::name('template')->where(['status'=>1,'type'=>5])->orderRaw('rand()')->limit(1)->value('img');
//                 $zt = ROOT_PATH.$zt;
                
//                 if($len > 8){  //两行显示
//                     $text1 = mb_substr($text, 0, 8,'utf8');
//                     $text2 = mb_substr($text, 8, $len,'utf8');
                    
                   
//                     if(!$template['location_z']){
//                         $fontBox = imagettfbbox($template['size'], 0, $zt, $text1);
//                         $template['location_z'] = ceil(450 - ($fontBox[2] / 2));
//                     }
//                     $img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
//                     $image1->text($text1,$zt,$template['size'],$template['color'],[$template['location_z'],$template['location_y']])->save($img2);
                    
//                     if(!$template['location_z']){
//                         $fontBox = imagettfbbox($template['size'], 0, $zt, $text2);
//                         $template['location_z'] = ceil(450 - ($fontBox[2] / 2));
//                     }
//                     $img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
//                     $image1->text($text2,$zt,$template['size'],$template['color'],[$template['location_z'],$template['location_y']+$template['interval']])->save($img2);
                    
//                 }else{  //一行显示
                    
//                     if(!$template['location_z']){
//                         $fontBox = imagettfbbox($template['size'], 0, $zt, $text);
//                         $template['location_z'] = ceil(450 - ($fontBox[2] / 2));
//                     }
//                     $img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
//                     $image1->text($text,$zt,$template['size'],$template['color'],[$template['location_z'],$template['location_y']])->save($img2);
//                 }
    
//                 //
//                 //
                
//                 //获取文字的宽度
                
            
//             }

//             $new_url[] = 'https://oa.yuxiang123.cn/'.$img2;
//         }
		


//         $data['new_url'] = $new_url;
//         return $data;

// 	}	


	public function getMoonshotAi(){
		set_time_limit(0);
		$title = $this->request->request('title','');
		$content = $this->request->request('content','');
		$user_id = $this->request->request('user_id','');
		$shop_id = $this->request->request('shop_id','');
		$ai_num = $this->request->request('ai_num',1);
		$text = $this->request->request('img_title','');
		$img = $this->request->request('img','');

		if(!$shop_id){
			$time = date('Y-m-d',time());
			$redis = redis_init();
			$redis_name = 'getMoonshotAi'.$time.$user_id;
			$num = $redis->get($redis_name);
			if($num > 2){
				$this->error('您今日免费使用次数已用完');
			}else{
				if(!$num){
					$redis->set($redis_name,1);
				}else{
					$redis->set($redis_name,$num+1);
				}
			}
		}

		//$content = str_replace(PHP_EOL, '', $content);
		//$title = str_replace(PHP_EOL, '', $title);
		//$query = '下面我将提供一个中文的内容模板，该内容模板包括“标题”和“内容”两部分，“标题”在20个字以内阐述。请按照模板的标题和内容去生成新的标题和内容，新标题要契合内容，新内容要和模板内容阐述的意思一致，并保留原有的段落结构，新内容的长度也基本跟原内容一致。标题：'.$title.'。内容：'.$content.'。';
		$sensitivity = '最佳,最好,最大,最低,最低级,最低价,最底最便宜,最具,最爱,最赚,最优,最优秀,最大程度,最高,最高级,最高档,最奢侈,史上最低价,最流行,最先进,最先进科学,最先进加工工艺,最先享受,最后,最新,最新科技,最新科学,最时尚,最符合,最舒适,最先,第一,中国第一,全网第一,销量第一,排名第一唯一一流,一天,第一品牌,NO.1,TOP1,最后一波,全国X大品牌之一,增加事业运招财进宝,护身平衡正负能量,万事亨通,旺人,转富招国等,首个,首选,独家,独家配方,首发,全网首发,全国首发,XX网独家,首次,首款,全国销量冠军,国家国家免检,国家领导人,填补国内空白,中国驰名，驰名商标,国际品质,点击领奖,恭喜获奖,全民免单,点击有惊喜,点击获取,点击转身,点击试穿,点击翻转,领取奖品,高档,正品,真皮,超赚,精准,资深,世界领先,遥遥领先,国家级,国家级产品,宇审级,顶级,项尖,尖端,顶级工艺,顶级享受,高级,极佳,绝佳,绝对,老字号,中国驰名商标,特供,专供,专家推荐,质量免检,无需国家质量检测,免抽检,国家领导人推荐,国家XX机关推荐,秒杀,抢爆,再不抢就没了,不会更便宜了,没有他就,错过就没机会了,万人疯抢,全民疯抢购,卖抢疯了极致,终极,国际级,世界级,全球级,千万级,特级,宇宙级最佳,最具,最好最高级,最最最便宜,最受欢迎,最聚拢,赚,顶尖,尖端顶级享受,极品极佳绝佳,绝对终极,致极,极具.完美,至,至尊,至臻,臻品,臻致,臻席,压轴,问鼎,空前,绝后,绝版,无双,非此莫属,巅峰,前所未有,无人能及,鼎级,鼎冠,定鼎,完美,翘楚之作,不可再生.不可复制,绝无仅有,寸土寸金,淋漓尽致,无与伦比,唯一,卓越,卓著,无效退款,不满意退款,零风险,特效,强效,速效,保证彻底解决,1天见效,100%有效,无依赖,无副作用,彻底消除,清除等,带来好运气，增强第六感,化解小人,增加事业运,招财进宝,健康富贵,提升运气,有助事业,护身,平衡正负能量,消除精神压力,调和气压,逢凶化吉,时来运转,万事亨通旺人,旺财,助吉避凶,仅此一过,唯一,第一品牌,NO.1,TOP.1,独一无二,全国第一,仅此一次,仅此一款,收益率,投资回报,保底收益,返本销售,无风险回报,快速回报,高收益回报,极致,极品,宇宙级,众筹,联系方式,电话,微信,京东,淘宝,B站,微博,抖音,关注,大牌,金牌,名牌,王牌,领袖品牌,至尊巅峰,奢侈,优秀,领导者,缔造者,创领品牌,领先上市,巨星,著名,掌门人,资深领袖,包回报,承诺,保底,保本稳赚,固定回报,年化收益,升值,众筹大牌,领袖,之王,王者,冠军,史无前例,前无古人,永久,万能,祖传,特效,无敌,纯天然,100%';
		if($title && $content){
			$query = '用提供的内容和标题生成'.$ai_num.'篇小红书推广笔记，包含标题、内容，内容最下面包含#话题，标题、内容都不要重复，标题长度不超过20个字，内容长度不超过200字或者原文长度的120%；话题自动查询相关热点话题自动生成。生成的内容可以添加点图标修饰并且有段落区分。生成的内容规避一下关键词：'.$sensitivity.'。标题：'.$title.'。内容：'.$content.'。';
		}elseif($title){
			$query = '用提供的标题，搜索相关互联网相关信息，生成'.$ai_num.'篇小红书推广笔记，包含标题、内容，内容最下面包含#话题，标题、内容都不要重复，标题长度不超过20个字，内容长度不超过200字；话题自动查询相关热点话题自动生成。生成的内容可以添加点图标修饰并且有段落区分。生成的内容规避一下关键词：'.$sensitivity.'。标题：'.$title.'。';
		}elseif($content){
			$query = '用提供的内容，搜索相关互联网相关信息，生成'.$ai_num.'  篇小红书推广笔记，包含标题、内容，内容最下面包含#话题，标题、内容都不要重复，标题长度不超过20个字，内容长度不超过200字；话题自动查询相关热点话题自动生成。生成的内容可以添加点图标修饰并且有段落区分。生成的内容规避一下关键词：'.$sensitivity.'。内容：'.$content.'。';
		}
		if(!$query){
			$this->error('参数错误');
		}
		
		$res = getMoonshotData($query,$user_id,$shop_id,$this->sensitivity);
		
		for ($i=0; $i < $ai_num; $i++) { 
			if($img || $text){
				if($text){
					$data = $this->disposeImg_1($img,3,$text,1);
				}else{
					$data = $this->disposeImg_1($img,2,$text,1);
				}

				if(!empty($res[$i])){
					$res[$i]['img'] = $data['new_url'];
					$res[$i]['class'] = 'dan';
					$res[$i]['ai_img_title'] = $text;
				}
			}else{
				$res[$i]['img'] = '';
				$res[$i]['class'] = 'dan';
				$res[$i]['ai_img_title'] = '';
			}
			
		}

		
		
		if($res){

			

			$this->success('操作成功',$res);
		}else{
			$this->error('AI生成错误,请重新操作');
		}
		
	}
		/* $arr = [];
		
		if($text){
			$data = $this->disposeImg_1($img,3,$text,1);
		}else{
			$data = $this->disposeImg_1($img,2,$text,1);
		}
		$shop = Shop::where(['id'=>$shop_id])->find();
		if(!$shop){
			$this->error('商户信息错误');
		}
	
		$res = getMoonshotData($query,$user_id,$shop_id);
		if($res['code'] == 1){
			$res['data']['img'] = $data['new_url'];
			$res['data']['class'] = 'dan';
			$res['data']['ai_img_title'] = $text;
			$arr[] = $res['data'];
		}elseif($res['code'] == -2){
			//重新请求一次
			$query = '注意：请区分“标题”和“内容”两部分!'.$query;
			$res = getMoonshotData($query,$user_id,$shop_id);
			if($res['code'] == 1){
				$res['data']['img'] = $data['new_url'];
				$res['data']['ai_img_title'] = $text;
				$res['data']['class'] = 'dan';
				$arr[] = $res['data'];
			}
		}
        
		if($arr){
			$this->success('操作成功',$arr);
		}else{
			$this->error('AI生成错误,请重新操作');
		}
 	*/
	
	// public function getMoonshotAi(){
	// 	set_time_limit(0);
	// 	$title = $this->request->request('title','');
	// 	$content = $this->request->request('content','');
	// 	$user_id = $this->request->request('user_id','');
	// 	$shop_id = $this->request->request('shop_id','');

	// 	//$content = str_replace(PHP_EOL, '', $content);
	// 	//$title = str_replace(PHP_EOL, '', $title);

	// 	$query = '下面我将提供一个中文的内容模板，该内容模板包括“标题”和“内容”两部分，“标题”在20个字以内阐述。请按照模板的标题和内容去生成新的标题和内容，新标题要契合内容，新内容要和模板内容阐述的意思一致，并保留原有的段落结构，新内容的长度也基本跟原内容一致。标题：'.$title.'。内容：'.$content.'。';
	// 	if(!$query){
	// 		$this->error('参数错误');
	// 	}
	// 	$shop = Shop::where(['id'=>$shop_id])->find();
	// 	if(!$shop){
	// 		$this->error('商户信息错误');
	// 	}
	// 	if($shop['ai_num'] <= 0 && $shop['balance'] < 0.05){
	// 		$this->error('账户余额不足');
	// 	}
	// 	$res = getMoonshotData($query,$user_id,$shop_id);
	// 	if($res['code'] == 1){
	// 		$this->success('获取成功',$res['data']);
	// 	}elseif($res['code'] == -2){
	// 		//重新请求一次
	// 		$query = '注意：请区分“标题”和“内容”两部分!'.$query;
	// 		$res = getMoonshotData($query,$user_id,$shop_id);
	// 		if($res['code'] == 1){
	// 			$this->success('获取成功',$res['data']);
	// 		}else{
	// 			$this->error('AI生成错误,请重新操作');
	// 		}
	// 	}else{
	// 		$this->error('AI生成错误,请重新操作');
	// 	}
	// }

	public function getAiChatGpt(){
		set_time_limit(0);
		$title = $this->request->request('title','');
		$content = $this->request->request('content','');
		$user_id = $this->request->request('user_id','');
		$shop_id = $this->request->request('shop_id','');

		//$content = str_replace(PHP_EOL, '', $content);
		//$title = str_replace(PHP_EOL, '', $title);

		$query = '下面我将提供一个中文的内容模板，该内容模板包括“标题”和“内容”两部分，“标题”在20个字以内阐述。请按照模板的标题和内容去生成新的标题和内容，新标题要契合内容，新内容要和模板内容阐述的意思一致，并保留原有的段落结构，新内容的长度也基本跟原内容一致。标题：'.$title.'。内容：'.$content.'。';
		if(!$query){
			$this->error('参数错误');
		}
		$shop = Shop::where(['id'=>$shop_id])->find();
		if(!$shop){
			$this->error('商户信息错误');
		}
		/* if($shop['ai_num'] <= 0 && $shop['balance'] < 0.05){
			$this->error('账户余额不足');
		} */
		$res = get_gpt_data($query,$user_id,$shop_id);
		if($res['code'] == 1){
			$this->success('获取成功',$res['data']);
		}elseif($res['code'] == -2){
			//重新请求一次
			$query = '注意：请区分“标题”和“内容”两部分!'.$query;
			$res = get_gpt_data($query,$user_id,$shop_id);
			if($res['code'] == 1){
				$this->success('获取成功',$res['data']);
			}else{
				$this->error('AI生成错误,请重新操作');
			}
		}else{
			$this->error('AI生成错误,请重新操作');
		}
	}


	public function getChatGpt(){
		set_time_limit(0);
		$query = $this->request->request('query','');
		if(!$query){
			$this->error('参数错误');
		}
		$api_key = "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";
		$curl = curl_init("https://www.iandkhair.com/cache/");
		$parameters = json_encode(["action"=>"gpt_query", "query"=>$query]);
		$header = ['X-API-Key:'. $api_key, 'Content-type:application/json', 'Accept-Charset:UTF-8'];
		$options = [
			CURLOPT_POST => true,
			CURLOPT_HTTPHEADER => $header,
			CURLOPT_POSTFIELDS => $parameters,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_TIMEOUT => 60,
			CURLOPT_SSL_VERIFYPEER => true,
			CURLOPT_SSL_VERIFYHOST => 2
		];

		curl_setopt_array($curl, $options);
		$response = curl_exec($curl);
		$httpcode = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
		curl_close($curl);

		$this->success('操作成功',$response);
	}


	//获取图片
	public function getImgs(){
		$img = $this->request->request('img','');
		$text = $this->request->request('text','');
		$num = $this->request->request('num',10);
		
		if($text){
			$data = $this->disposeImg_1($img,3,$text,$num);
		}else{
			$data = $this->disposeImg_1($img,2,$text,$num);
		}
		$data['img'] = $img;
		$this->success('获取成功',$data);
	}

	//生成处理后图
	public function disposeImg_1($background = '',$type = '',$text = '',$num = 1){
		$is_bj = 0;
		if($background){
			$is_bj = 1;
		}
		$background = $background ? $background : $this->request->request('background','');
		$type = $type ? $type : $this->request->request('type',2);
		$text = $text ? $text : $this->request->request('text','');

		//未传背景图
		if(!$background){
			$background = Db::name('template')->where(['status'=>1,'type'=>1])->orderRaw('rand()')->limit(1)->value('img');
		}
		
		$background_arr = explode('uploads',$background);
		$background = 'uploads'.$background_arr[1];
	
		$image = \think\Image::open($background);
		$img = 'uploads/invite/'.time().rand(1000, 9999).'.png';
		// 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
		$image->thumb(900,1200,\think\Image::THUMB_CENTER)->save($img);
		$ids = '0';
		$bj_ids = '0';
		for ($i=0; $i < $num; $i++) { 
			if($is_bj == 0){
				$background = Db::name('template')->where(['status'=>1,'type'=>1,'id'=>['neq',$bj_ids]])->orderRaw('rand()')->limit(1)->find();
				$bj_ids .= ','.$background['id'];
				$background_arr = explode('uploads',$background['img']);
				$background = 'uploads'.$background_arr[1];
			
				$image = \think\Image::open($background);
				$img = 'uploads/invite/'.time().rand(1000, 9999).'.png';
				// 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
				$image->thumb(900,1200,\think\Image::THUMB_CENTER)->save($img);
			}
			
			if($type == 2){
				
				//获取模版
				$template =  Db::name('template')->where(['status'=>1,'type'=>$type,'id'=>['neq',$ids]])->orderRaw('rand()')->limit(1)->find();	
				$ids .= ','.$template['id'];
				$template_arr = explode('uploads',$template['img']);
				$img1 = 'uploads'.$template_arr[1];
				$image = \think\Image::open($img);
				$img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
				$image->water($img1,[0,0])->save($img2);
			}elseif( $type == 3 && $text){
				$len =  mb_strlen($text, 'utf8');
				if($len > 16){
					$this->error('不可超过16个字');
				}
				if($len > 8){  //两行显示
					$where = [
						'status'=>1,
						'type'=>$type,
						'pre_line'=>['>=',$len],
						'line'=>2,
						'id'=>['neq',$ids]
					];
				}else{  //一行显示
					$where = [
						'status'=>1,
						'type'=>$type,
						'pre_line'=>['>=',$len],
						'line'=>1,
						'id'=>['neq',$ids]
					];
					
				}
			
				//获取模版
				$template =  Db::name('template')->where($where)->orderRaw('rand()')->limit(1)->find();	
			
				if(!$template){
					$this->error('操作错误');
				}
				$ids .= ','.$template['id'];
				$template_arr = explode('uploads',$template['img']);
				$img1 = 'uploads'.$template_arr[1];

				$image = \think\Image::open($img);
				$img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
				$image->water($img1,[0,0])->save($img2);
				
				$image1 = \think\Image::open($img2);
				
				$zt = Db::name('template')->where(['status'=>1,'type'=>5])->orderRaw('rand()')->limit(1)->value('img');
				$zt = ROOT_PATH.$zt;
				
				if($len > 8){  //两行显示
					$text1 = mb_substr($text, 0, 8,'utf8');
					$text2 = mb_substr($text, 8, $len,'utf8');
					
				
					if(!$template['location_z']){
						$fontBox = imagettfbbox($template['size'], 0, $zt, $text1);
						$template['location_z'] = ceil(450 - ($fontBox[2] / 2));
					}
					$img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
					$image1->text($text1,$zt,$template['size'],$template['color'],[$template['location_z'],$template['location_y']])->save($img2);
					
					if(!$template['location_z']){
						$fontBox = imagettfbbox($template['size'], 0, $zt, $text2);
						$template['location_z'] = ceil(450 - ($fontBox[2] / 2));
					}
					$img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
					$image1->text($text2,$zt,$template['size'],$template['color'],[$template['location_z'],$template['location_y']+$template['interval']])->save($img2);
					
				}else{  //一行显示
					
					if(!$template['location_z']){
						$fontBox = imagettfbbox($template['size'], 0, $zt, $text);
						$template['location_z'] = ceil(450 - ($fontBox[2] / 2));
					}
					$img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
					$image1->text($text,$zt,$template['size'],$template['color'],[$template['location_z'],$template['location_y']])->save($img2);
				}

				//
				//
				
				//获取文字的宽度
				
			
			}

			$new_url[] = 'https://oa.yuxiang123.cn/'.$img2;
		}
		


		$data['new_url'] = $new_url;
		return $data;

	}	
	
	


	
	//图片生成
	public function generation_tasks(){
		$prompt = $this->request->request('prompt');
		$type = $this->request->request('type');
		$img_url = $this->request->request('img_url');

        $id = $this->set_models();
		$token = $this->encode_jwt_token();
		$parameters = json_encode(["model_id"=>$id,'prompt'=>$prompt, "type"=>$type,"img_url"=>$img_url]);
        
		$res = getMiaohuaData($token,$parameters);

		if(!empty($res['task_id'])){
			$url = 'https://api.sensenova.cn/v1/imgen/internal/generation_tasks/'.$res['task_id'];
			$token = $this->encode_jwt_token();
			$res = getModelsData($token,$url);
			$this->success($res);
		}

		return $res['task_id'];
    }
    
	//模型信息查询
	public function set_models(){
        $token = $this->encode_jwt_token();
  
        $res = getModelsData($token);
   
		$id = $res['data'][1]['id'];

		return $id;
    }
    
	//权限鉴权
    public function encode_jwt_token($ak = '71BD02CA207C4A74867C0D0F9C175F1B',$sk='C047D0BA4FAE46BC8AE6C060CAE2A677'){
        $headers = [
            'alg'=>'HS256',
            'typ'=>'JWT'
        ];
        
        $payload =[
            'iss'=> $ak,
            'exp' => time()+ 1800,
            'nbf'=> time()-5
        ];
        // 1! 填写您期望的有效时间，此处示例代表当前时间+30分钟'nbf'=> time()-5，1! 填写您期望的生效时间，此处示例代表当前时间-5秒
        $token=JWT::encode($payload,$sk,'HS256',null,$headers);
        return $token;
        // $authorization=encode iwt token($ak，$sk);
    }



	public function get_location_by_lnglat()
	{
		$lng = $this->request->request('lng','');
		$lat = $this->request->request('lat','');
		$url = "http://restapi.amap.com/v3/geocode/regeo?key=102c66c5bc1d0ad41cb891e772802342&location={$lng},{$lat}";
	 
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$response = curl_exec($ch);
		curl_close($ch);
	 
		$response_data = json_decode($response, true);
	 
		if ($response_data && $response_data['status'] == '1' && isset($response_data['regeocode'])) {
			$address = $response_data['regeocode']['addressComponent'];
			$this->success('操作成功',$address);
		} else {
			$this->error('操作失败');
		}
	}

	
    //联系我们
	public function relation(){
		$data = $this->request->request();
		$data['add_time'] = time();
		Relation::insert($data);
		$this->success('操作成功');
	}

	//获取新闻资讯
	public function get_article(){
		$id = $this->request->request('id','');
		if($id){
			$list = Article::where(['id'=>$id])->find();
		}else{
			$list = Article::where(['type'=>6])->order('add_time desc')->limit(0,10)->select();
		}
		$this->success('操作成功',$list);
	}


	public function dy_login(){
        $code = $this->request->request('code');
        $openid = $this->request->request('openid','');
        $mobile = $this->request->request('mobile','');	
        $avatar = $this->request->request('avatar','');
        $nickname = $this->request->request('nickname','');
        $invite_user_id = $this->request->request('invite_user_id',0);
		if($mobile){
            $user=User::where(array('mobile'=>$mobile,'status'=>['in','1,0']))->find();
			$is_new = 0;
    		if($user){
	    	    $token=$user['token'];
	    	    if($user['status'] == 0){
                    $this->error('您的账号已被限制登陆了');
		        }
				$this->success('登录成功',['token'=>$token,'user'=>$user,'is_new'=>$is_new]);
	    	}else{
				//第一次注册储存缓存 防止重复点击注册多个用户
				$redis = redis_init();
				$redis_name = 'userInfo'.$mobile;
				$info = $redis->get($redis_name);
				if(!$info){
					$redis->set($redis_name,1);
				}else{
					$this->error('请勿重复点击');
				}
				//账号注册时需要开启事务,避免出现垃圾数据
				Db::startTrans();
				try {
					//创建之前查询手机号是否已经注册
					$user=User::where(array('mobile'=>$mobile,'status'=>['in','1,0']))->find();
					if($user){
						Db::commit();
						$this->error('请勿重复点击');
					}
					$nickname = $this->repetition_nickname('用户'.substr($mobile,7,4));
					$token=md5(md5(date("ymdHis").rand(100000,999999)));
					$user['invite_user_id']	=$invite_user_id;
					$user['mobile']		    =$mobile;
					$user['nickname']		=$nickname;
					$user['avatar']			=$avatar ? $avatar : 'https://'.$_SERVER['HTTP_HOST'].'/assets/portrait/'.rand(1,17).'.png';
					$user['openid']			=$openid;
					$user['bgimg']			=$this->configuration['default_bgimg'];
					$user['login_source']   = 'dy';
					$user['token']			=$token;
					$user['last_login_time']=time();
					$user['add_time']		=time();
					$user_id=User::insertGetId($user);
					$user['id']=$user_id;
					$is_new = 1;
					Db::commit();
					$redis->set($redis_name,'');
					$this->success('登录成功',['token'=>$token,'user'=>$user,'is_new'=>$is_new]);
				} catch (Exception $e) {
					Db::rollback();
					$redis->set($redis_name,'');
					
					$this->error('操作失败');
				}
            }
           
        }else{
            $user=User::where(array('nickname'=>$nickname,'avatar'=>$avatar,'status'=>['in','1,0']))->find();
			$is_new = 0;
    		if($user){
	    	    $token=$user['token'];
	    	    if($user['status'] == 0){
                    $this->error('您的账号已被限制登陆了');
		        }
				$this->success('登录成功',['token'=>$token,'user'=>$user,'is_new'=>$is_new]);
	    	}else{
				//第一次注册储存缓存 防止重复点击注册多个用户
				$redis = redis_init();
				$redis_name = 'userInfo'.$avatar.$nickname;
				$info = $redis->get($redis_name);
				if(!$info){
					$redis->set($redis_name,1);
				}else{
					$this->error('请勿重复点击');
				}
				//账号注册时需要开启事务,避免出现垃圾数据
				Db::startTrans();
				try {
					$token=md5(md5(date("ymdHis").rand(100000,999999)));
					$user['invite_user_id']	=$invite_user_id;
					$user['nickname']		=$nickname;
					$user['avatar']			=$avatar ? $avatar : 'https://'.$_SERVER['HTTP_HOST'].'/assets/portrait/'.rand(1,17).'.png';
					$user['openid']			=$openid;
					$user['bgimg']			=$this->configuration['default_bgimg'];
					$user['login_source']   = 'dy';
					$user['token']			=$token;
					$user['last_login_time']=time();
					$user['add_time']		=time();
					$user_id=User::insertGetId($user);
					$user['id']=$user_id;
					$is_new = 1;
					Db::commit();
					$redis->set($redis_name,'');
					$this->success('登录成功',['token'=>$token,'user'=>$user,'is_new'=>$is_new]);
				} catch (Exception $e) {
					Db::rollback();
					$redis->set($redis_name,'');
					
					$this->error('操作失败');
				}
            }
           
        }
    }

	//抖音授权登录
    public function dy_get_openid()
    {
		$code = $this->request->request('code','');
        if(!$code)return ['code'=>201,'msg'=>'请重新授权登录','data'=>''];
        $arr = [
            'appid'     => 'tt414337fede7516a001',  //秒宣
            'secret'    => '12881ce1a3f2d97c7678a5a9eb261ddcbbf5fe3a', //秒宣
            'code'      => $code,
            'anonymous_code' => "",
        ];
        // 获取授权信息
        $url = 'https://developer.toutiao.com/api/apps/v2/jscode2session';
        // 获取信息
        $res = json_decode(httpRequest($url,$arr),true);
        if($res['err_tips'] == 'success'){
			$this->success('获取成功',$res['data']);
        }else{
			$this->error('获取失败');
        }
    }

	public function dyGetPhone(){
		$code = $this->request->request('code');
		$iv = $this->request->request('iv');
		$sign = $this->request->request('encryptedData');
		$phone = '';
		$resjson = $this->httpCurl('https://developer.toutiao.com/api/apps/jscode2session?appid=tt414337fede7516a001&secret=12881ce1a3f2d97c7678a5a9eb261ddcbbf5fe3a&code='.$code,[]);
		if ($resjson['error']==0){
		$key = $resjson['session_key'];
		$openid = $resjson['openid'];
		//解密数据
		$phone = openssl_decrypt(base64_decode($sign,true), 'AES-128-CBC', base64_decode($key), OPENSSL_RAW_DATA, base64_decode($iv));
		if (!$phone){
			$this->error('授权登陆失败,请重试');
		}else{
			$phone = json_decode($phone,true)['phoneNumber'];
			$this->success('操作成功',$phone);
		}
		}else{
			$this->error('授权登陆失败,请重试');
		}
	}
		
	function httpCurl($url,$data=null){
		//初始化
		$ch = curl_init();
		
		//设置选项，包括URL
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		if(!empty($data)){
		curl_setopt($ch,CURLOPT_POST,1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
		}
		$output = curl_exec($ch);
		curl_close($ch);
		
		return json_decode($output,true);
	}
}
